package init

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"user-server/basic/config"
	"user-server/basic/global"
	"user-server/inaternal/model"
)

func init() {
	ConfigInit()
	MysqlInit()
	RedisInit()
}
func ConfigInit() {
	v := viper.New()
	v.SetConfigFile("./dev.yaml")
	err := v.ReadInConfig()
	if err != nil {
		return
	}
	nacos := config.Nacos{}
	err = v.Unmarshal(&nacos)
	global.NacosConfig = nacos
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.NameSpaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.NacosConfig.IpAddr,
			ContextPath: "/nacos",
			Port:        global.NacosConfig.Port,
			Scheme:      "http",
		},
	}
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group})
	apiConfig := config.ApiConfig{}
	json.Unmarshal([]byte(content), &apiConfig)
	global.GlobalConfig = apiConfig
}
func MysqlInit() {
	var err error
	dsn := fmt.Sprintf("root:8b7b2201c07309906f80c4af2fdd6b54@tcp(14.103.243.155:3306)/work?charset=utf8mb4&parseTime=True&loc=Local")
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	} else {
		log.Println("mysql init success")
	}
	err = global.DB.AutoMigrate(&model.Video{})
	if err != nil {
		panic(err)
	} else {
		log.Println("数据库表迁移成功")
	}
}
func RedisInit() {
	global.RDB = redis.NewClient(&redis.Options{
		Addr:     global.GlobalConfig.Redis.Addr,
		Password: global.GlobalConfig.Redis.Password,
		DB:       global.GlobalConfig.Redis.DB,
	})
	err := global.RDB.Ping(context.Background()).Err()
	if err != nil {
		panic(err)
	} else {
		log.Println("redis init success")
	}
}
